//
//  LoginViewController.m
//  CI
//
//  Created by tongbu_jinzhongjun on 14-10-19.
//  Copyright (c) 2014年 tongbu_jinzhongjun. All rights reserved.
//

#import "LoginViewController.h"
#import "DetailViewController.h"
#import "Constants.h"
#import <Objection.h>
#import "NetWork.h"
#import "NetWorkRequest.h"
#import "HomeViewController.h"
#import "UserDefaultSave.h"
#import <SVProgressHUD.h>
#import "UserProduct.h"
#import <CoreData+MagicalRecord.h>
#import "JAlertViewHelper.h"



@interface LoginViewController ()<UISplitViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [self updateProductToServer];
                break;
                
            default:
                break;
        }
    }];
    
    self.loginButton.backgroundColor = UIColorFromRGB(0x005b9a);
    self.loginButton.layer.cornerRadius = 3.f;
    
    self.top_line.backgroundColor = self.center_line.backgroundColor = self.bottom_line.backgroundColor = UIColorFromRGB(0xd2d1d6);
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignTextField:)]];
    
}

-(void) updateProductToServer {
    
    NSArray *array = [UserProduct MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"state == 1"]];
    NetWorkRequest *request = [[JSObjection defaultInjector] getObject:[NetWorkRequest class]];
    UserDefaultSave *save = [[JSObjection defaultInjector] getObject:[UserDefaultSave class]];
    for (UserProduct *pro in array ) {
        [request postProductInfoWithParameter:@{@"hospitalId":pro.hospital_id,
                                                @"typeId":pro.type_id,
                                                @"companyId":pro.company_id,
                                                @"userId":[save getUserId],
                                                @"productId":pro.product_id,
                                                @"count":pro.count}
                                      success:^{
                                          [pro MR_deleteEntity];
                                      } failure:^{
                                      }];
    }
    
}


-(void)resignTextField:(UITapGestureRecognizer*) guesture {
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)login:(UIButton *)sender {
    sender.enabled = NO;
    //判断是否输入了用户名和密码
    
    NSString *userName = self.userNameTextField.text;
    NSString *password = self.passwordTextField.text;
    if ((!self.userNameTextField.text || !self.passwordTextField.text) ||([userName isEqualToString:@""] || [password isEqualToString:@""]) ) {
        
        sender.enabled = YES;
        [[JAlertViewHelper shareAlterHelper] showTint:@"用户名和密码不能为空" duration:1.f];
        return;
    }
    
    if ([AFNetworkReachabilityManager sharedManager].reachable) {
        [self onlineLoginWithUserName:userName password:password];
        sender.enabled = YES;
    }else {
        [self offlineLoginWithUserName:userName password:password];
        sender.enabled = YES;
    }
}

-(void) onlineLoginWithUserName:(NSString *)userName password:(NSString*)password {
    [SVProgressHUD showWithStatus:@"正在登录..."];
    NSDictionary *parameter = @{@"name":userName,@"password":password};
    
    JSObjectionInjector *injector = [JSObjection defaultInjector];
    NetWorkRequest *request = [injector getObject:[NetWorkRequest class]];
    [request loginWithParameter:parameter success:^{
        //        [self loginSuccess];
        [self loginHome];
    } failure:^{
        
        [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
    }];
}

-(void) offlineLoginWithUserName:(NSString*)userName password:(NSString*)password {
    UserDefaultSave *userSave = [[JSObjection defaultInjector]getObject:[UserDefaultSave class]];
    NSString *userName_save = [userSave getUserName];
    NSString *password_save = [userSave getPassword];
    if ([userName isEqualToString:userName_save] && [password isEqualToString:password_save]) {
        [self loginHome];
    }else  {
        [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
    }
}

-(void) loginHome {
    
    [SVProgressHUD showSuccessWithStatus:@"登录成功"];
    HomeViewController *home = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"home"];
    [self presentViewController:home animated:YES completion:^{
        
        UserDefaultSave *userSave = [[JSObjection defaultInjector]getObject:[UserDefaultSave class]];
        [userSave saveUserName:self.userNameTextField.text];
        [userSave savePassword:self.passwordTextField.text];
        
    }];
}

-(void) loginSuccess {
    UISplitViewController *splitViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"split_controller"];
    
    UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
    navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
    splitViewController.delegate = self;
    
    
    UIViewController *view1 = [[UIViewController alloc]init];
    UIViewController *view2 = [[UIViewController alloc]init];
    UIViewController *view3 = [[UIViewController alloc]init];
    UIViewController *view4 = [[UIViewController alloc]init];
    
    view1.view.backgroundColor = [UIColor redColor];
    view2.view.backgroundColor = [UIColor blueColor];
    view3.view.backgroundColor = [UIColor greenColor];
    view4.view.backgroundColor = [UIColor whiteColor];
    
    UITabBarController *tabbarController = [[UITabBarController alloc] init];
    tabbarController.viewControllers = @[view1,splitViewController,view2,view3,view4];
    tabbarController.selectedIndex = 1;
    [self presentViewController:tabbarController animated:YES completion:nil];
    [[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:@"tabbar_background"]];
}


#pragma mark - Split view

- (BOOL)splitViewController:(UISplitViewController *)splitViewController collapseSecondaryViewController:(UIViewController *)secondaryViewController ontoPrimaryViewController:(UIViewController *)primaryViewController {
    if ([secondaryViewController isKindOfClass:[UINavigationController class]] && [[(UINavigationController *)secondaryViewController topViewController] isKindOfClass:[DetailViewController class]] && ([(DetailViewController *)[(UINavigationController *)secondaryViewController topViewController] detailItem] == nil)) {
        // Return YES to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
        return YES;
    } else {
        return NO;
    }
}



@end
